package com.link.play.fit.ai.ui.guide

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.databinding.FgFastingTimeBinding
import com.link.play.fit.ai.ui.dialog.SetTimeDialog
import com.link.play.fit.ai.ui.guide.ac.GuidePbAc
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.time.LocalTime
import java.util.Locale


class FastingTimeFg : BasePageFragment<FgFastingTimeBinding>(FgFastingTimeBinding::inflate) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val activity = (requireActivity() as GuidePbAc)
        val data = activity.viewModel.userGuideState

        lifecycleScope.launch {
            data.collectLatest {
                upDateTime(it.fastingGoal, it.fastingStartTime)
            }
        }

        binding.tvStartTime.setOnClickListener {

            SetTimeDialog(activity).showDialog(data.value.fastingStartTime.ifEmpty { "08:10:AM" }) { time ->

                data.update { it.copy(fastingStartTime = time) }

                upDateTime(data.value.fastingGoal, time)
            }

        }
    }

    fun upDateTime(fastingGoal: Int, fastingStartTime: String) {
        if (fastingStartTime == "") return
        val startTime = convertTo24HourFormat(fastingStartTime)
        binding.tvStartTime.text = startTime
        val hour = when (fastingGoal) {
            0 -> 12
            1 -> 10
            2 -> 8
            else -> 0
        }
        binding.tvEndTime.text = addHoursToTime(startTime, hour)
        binding.lls.visibility = View.GONE
    }

    fun convertTo24HourFormat(time12h: String): String {
        // 定义输入的时间格式（12小时制）
        val time12hFormat = SimpleDateFormat("hh:mm:a", Locale.ENGLISH)
        // 定义输出的时间格式（24小时制）
        val time24hFormat = SimpleDateFormat("HH:mm", Locale.ENGLISH)

        // 将输入的时间字符串解析为Date对象
        val time = time12hFormat.parse(time12h)
        // 将Date对象格式化为24小时制的时间字符串
        return time24hFormat.format(time)
    }

    @SuppressLint("DefaultLocale")
    fun addHoursToTime(time: String, hoursToAdd: Int): String {
        // 将输入的时间字符串解析为 LocalTime 对象
        val initialTime = LocalTime.parse(time)
        // 将指定小时数加到时间上
        val resultTime = initialTime.plusHours(hoursToAdd.toLong())
        // 返回格式化后的时间字符串（HH:mm 格式）
        return String.format("%02d:%02d", resultTime.hour, resultTime.minute)
    }

}